package com.ev.filesConverting.server.Impl;

import com.ev.filesConverting.server.FilesConvertingServer;
import org.jodconverter.DocumentConverter;
import org.jodconverter.document.DefaultDocumentFormatRegistry;
import org.jodconverter.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
//@Service
public class FilesConvertingServerImpl implements FilesConvertingServer {
    @Autowired private DocumentConverter documentConverter;

    /**
     * 文件转换
     * @return
     */
    @Override
    public OutputStream convert2PDF(InputStream  in, String suffix)
    {
        OutputStream baos = new ByteArrayOutputStream();
        try
        {
            if(suffix.equals("doc"))
            {
                documentConverter.convert(in)
                        .as(DefaultDocumentFormatRegistry.DOC)
                        .to(baos)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            }
            if(suffix.equals("docx"))
            {
                documentConverter.convert(in)
                        .as(DefaultDocumentFormatRegistry.DOCX)
                        .to(baos)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            }
            if(suffix.equals("xls"))
            {
                documentConverter.convert(in)
                        .as(DefaultDocumentFormatRegistry.XLS)
                        .to(baos)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            }
            if(suffix.equals("xlsx"))
            {
                documentConverter.convert(in)
                        .as(DefaultDocumentFormatRegistry.XLSX)
                        .to(baos)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            }
            if(suffix.equals("ppt"))
            {
                documentConverter.convert(in)
                        .as(DefaultDocumentFormatRegistry.PPT)
                        .to(baos)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            }
            if(suffix.equals("pptx"))
            {
                documentConverter.convert(in)
                        .as(DefaultDocumentFormatRegistry.PPTX)
                        .to(baos)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            }
            return baos;
        }
        catch (OfficeException e)
        {
            return  null;
        }
    }
}
